package org.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.entity.Books;
import org.service.BooksService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Books)表控制层
 *
 * @author makejava
 * @since 2021-10-13 08:41:09
 */
//增加了@RestController之后，默认会解析字符串，不会跳转
@RestController
@RequestMapping("books")
public class BooksController {
    /**
     * 服务对象
     */
    @Resource
    private BooksService booksService;

    /**
     * 通过主键查询单条数据
     *  如何访问这个控制器的方法调用：/books/selectOne?id=xxx`
     *  参数名字和url参数名字相同就可以
     * @param id 主键
     * @return 单条数据的json字符串
     */
    @GetMapping("selectOne")
    public Books selectOne(Integer id) {
        return this.booksService.queryById(id);
    }
    //jackson01方法返回json字符串
    @RequestMapping(value = "jackson01")
    public String jackson01() throws JsonProcessingException {
        //创建一个jackson的对象映射
        ObjectMapper mapper = new ObjectMapper();
        //构建一个实体对象
        Books books = new Books(10,"测试书籍10",3,"测试作者02");
        //将实体对象的结果转换为json格式
        String string = mapper.writeValueAsString(books);
        return string;
    }
    //jackson02返回对象的toString
    @RequestMapping(value = "jackson02")
    public String jackson02() {
        //构建一个实体对象
        Books books = new Books(10,"测试书籍10",3,"测试作者02");
        return books.toString();
    }
    //方式一：list转换为普通字符串
    @RequestMapping(value = "list01")
    public String list01(){
        List<Books> booksList = booksService.queryAllByLimit(0, 5);
        return booksList.toString();
    }
    //方式二：使用jackson将list装换json字符串
    @RequestMapping(value = "list02")
    public String list02() throws JsonProcessingException {
        List<Books> booksList = booksService.queryAllByLimit(0, 5);
        ObjectMapper mapper = new ObjectMapper();
        //将list字符串转换为json字符串输出
        String string = mapper.writeValueAsString(booksList);
        return string;
    }
    //方式三：直接通过List得到json字符串
    @GetMapping("list03")
    public List<Books> list03() {
        return this.booksService.queryAllByLimit(0,5);
    }
}